package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

	@Autowired
	private TransactionTemplate transactionTemplate;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		
		System.out.println("事务执行前---》"+getCount());
		
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
			
				//事务执行中
				jdbcTemplate.execute("insert into user(id,username,password) values(1,1,1)");
				System.out.println("事务执行中---》"+getCount());
				//回滚W
				transactionStatus.setRollbackOnly();
			}
		});
		System.out.println("事务执行后---》"+getCount());
		
	}
	
	//统计数据条数
	public long getCount() {
		return jdbcTemplate.queryForObject("select count(*) from user", Long.class);
	}

}
